package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author syf
 * @version 1.0
 * @date 2019/08/19 20:05
 * @Description TODO:微信支付工具类
 */
@Slf4j
@Component
public class PayHelper {

    @Autowired
    private WXPay wxPay;

    @Autowired
    private WXPayConfigImpl wxPayConfig;
    /**
     *调用微信的统一单接口，返回二维码连接
     * @param orderId 订单id
     * @return
     */
    public String createWxPayUrl(Long orderId,Long actualFee){
        // 请求参数：
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "支付成功");
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", actualFee.toString());
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", wxPayConfig.getNotifyUrl());
        data.put("trade_type", wxPayConfig.getPayType());  // 此处指定为扫码支付

        try {
            Map<String, String> resp = wxPay.unifiedOrder(data);
            //做通信标识和交易标识的验证
            checkWxPayCode(resp);
            log.info("[微信支付二维码成功】");
            return resp.get("code_url");//二维码链接
        } catch (Exception e) {

           throw new RuntimeException(e);
        }
    }

    public void checkWxPayCode(Map<String, String> resp) {
        //先判断通信标识
        if (resp.get("return_code").equals("FAIL")) {
            //微信支付失败
            log.error("【微信支付生成二维码异常】微信异常！");
            throw new LyException(ExceptionEnum.WX_PAY_ERROR);
        }
        //判断交易标识
        if (resp.get("return_code").equals("FAIL")) {
            //微信支付失败
            log.error("【微信支付生成二维码异常】微信异常！异常信息为：{}",resp.get("err_code_des"));
            throw new LyException(ExceptionEnum.WX_PAY_ERROR);
        }
    }
}
